<template>
  <a-card :bordered="false">
    <div class="map-container">
      <div id="container" class="map"></div>
      <div v-if="mapError" class="error-message">
        <a-alert type="error" :message="mapError" banner />
      </div>
      <div class="map-controls" v-if="!mapError">
        <a-button-group style="margin-bottom: 10px">
          <a-button type="primary" @click="toggle3D" :loading="viewChanging">
            {{ is3D ? '切换平面' : '切换3D' }}
          </a-button>
          <a-button @click="toggleTraffic">
            {{ showTraffic ? '隐藏路况' : '显示路况' }}
          </a-button>
          <a-button @click="toggleBuildings">
            {{ showBuildings ? '隐藏建筑' : '显示建筑' }}
          </a-button>
        </a-button-group>
        <div>
          <a-button-group>
            <a-button @click="resetView">
              <a-icon type="reload" />重置视角
            </a-button>
            <a-button @click="toggleMapStyle">
              {{ isDarkStyle ? '浅色地图' : '深色地图' }}
            </a-button>
          </a-button-group>
        </div>
      </div>

      <!-- 地图标记信息窗口 -->
      <div class="info-window" v-if="infoWindowVisible">
        <a-card size="small" title="位置信息">
          <p><strong>名称:</strong> {{ currentMarker.name }}</p>
          <p><strong>地址:</strong> {{ currentMarker.address }}</p>
          <p><strong>坐标:</strong> {{ currentMarker.position.join(', ') }}</p>
          <a-button type="primary" size="small" @click="infoWindowVisible = false">关闭</a-button>
        </a-card>
      </div>

      <!-- 无人机信息面板 -->
      <div class="drone-info" v-if="selectedDrone">
        <a-card title="无人机信息" size="small">
          <p>编号: {{ selectedDrone.id }}</p>
          <p>位置: {{ selectedDrone.position.join(', ') }}</p>
          <p>高度: {{ selectedDrone.altitude }}米</p>
          <p>速度: {{ selectedDrone.speed }}km/h</p>
          <p>电量: {{ selectedDrone.battery }}%</p>
          <p>状态: {{ selectedDrone.status }}</p>
        </a-card>
      </div>
    </div>
  </a-card>
</template>

<script>
/* eslint-disable no-undef */
export default {
  name: 'ImplementationMap',
  data () {
    return {
      map: null,
      is3D: true,
      trafficLayer: null,
      buildingLayer: null,
      showTraffic: false,
      showBuildings: true,
      isDarkStyle: false,
      mapError: null,
      mapStyles: {
        light: 'amap://styles/fresh',
        dark: 'amap://styles/dark'
      },
      // 信息窗口相关
      infoWindowVisible: false,
      currentMarker: {
        name: '',
        address: '',
        position: []
      },
      // 地标点
      landmarks: [
      ],
      isSatellite: false,
      markers: {}, // 存储所有无人机标记
      selectedDrone: null, // 当前选中的无人机
      drones: [ // 模拟无人机数据
        {
          id: 'drone-001',
          position: [106.504962, 29.533155],
          altitude: 100,
          speed: 30,
          battery: 85,
          status: '正常巡航'
        },
        {
          id: 'drone-002',
          position: [106.514962, 29.543155],
          altitude: 120,
          speed: 25,
          battery: 90,
          status: '任务执行中'
        }
      ],
      viewChanging: false, // 视图切换中状态
      satelliteLayer: null,
      roadNetLayer: null,
      controlBar: null // 存储控制条引用
    }
  },
  mounted () {
    // 检查AMap是否已加载
    if (typeof AMap === 'undefined') {
      this.mapError = '高德地图API未加载，请检查网络连接或API密钥配置'
      console.error('AMap is not defined. Make sure the API is loaded correctly.')

      this.loadAMapScript()
      return
    }

    // 延迟初始化地图，确保DOM已完全渲染
    this.$nextTick(() => {
      try {
        this.initMap()
        // 模拟实时更新无人机位置
        this.startDroneSimulation()
      } catch (error) {
        this.mapError = `地图初始化失败: ${error.message}`
        console.error('Map initialization error:', error)
      }
    })
  },
  methods: {
    // 动态加载高德地图API
    loadAMapScript () {
      const script = document.createElement('script')
      script.type = 'text/javascript'
      script.async = true
      // 加载更多插件，以支持3D视图和地图控件
      script.src = 'https://webapi.amap.com/maps?v=2.0&key=2d33ca727354eb67d75cb29743d39f10&plugin=Map3D,AMap.Scale,AMap.ToolBar,AMap.ControlBar'

      script.onerror = () => {
        this.mapError = '高德地图API加载失败，请检查网络连接'
      }

      script.onload = () => {
        if (typeof AMap !== 'undefined') {
          this.mapError = null
          this.initMap()
        }
      }

      document.head.appendChild(script)
    },

    initMap () {
      // 创建地图实例
      this.map = new AMap.Map('container', {
        zoom: 12,
        center: [106.504962, 29.533155], // 重庆市中心坐标
        viewMode: '3D',
        pitch: 45,
        rotation: -15,
        mapStyle: this.mapStyles.light
      })

      // 监听地图加载完成事件
      this.map.on('complete', () => {
        console.log('地图加载完成')
        // 初始化图层
        this.initLayers()
        // 添加控件
        this.addMapControls()
        // 添加重庆市边界
        this.addDistrictBoundary()
        // 添加地标标记
        this.addLandmarks()
        // 添加无人机标记
        this.initDroneMarkers()
      })

      // 监听地图加载错误
      this.map.on('error', (error) => {
        this.mapError = `地图加载错误: ${error.message}`
        console.error('Map loading error:', error)
      })
    },

    initLayers () {
      // 实时路况图层
      this.trafficLayer = new AMap.TileLayer.Traffic({
        zIndex: 10,
        opacity: 0.8
      })
      this.trafficLayer.setMap(null)

      // 建筑物图层
      this.buildingLayer = new AMap.Buildings({
        zIndex: 11,
        heightFactor: 2,
        zooms: [12, 20]
      })
      this.buildingLayer.setMap(this.map)
    },

    addMapControls () {
      // 添加 3D 控制控件
      this.map.plugin(['AMap.ControlBar', 'AMap.Scale', 'AMap.ToolBar'], () => {
        // 3D 控制控件
        this.map.addControl(new AMap.ControlBar({
          position: {
            right: '10px',
            top: '10px'
          }
        }))

        // 比例尺
        this.map.addControl(new AMap.Scale())

        // 工具条
        this.map.addControl(new AMap.ToolBar({
          position: {
            right: '10px',
            top: '80px'
          }
        }))
      })
    },

    addDistrictBoundary () {
      this.map.plugin('AMap.DistrictSearch', () => {
        const districtSearch = new AMap.DistrictSearch({
          level: 'district',
          extensions: 'all',
          subdistrict: 1
        })

        districtSearch.search('重庆市', (status, result) => {
          if (status === 'complete' && result.districtList && result.districtList[0].boundaries) {
            const bounds = result.districtList[0].boundaries
            bounds.forEach(path => {
              new AMap.Polygon({
                path,
                strokeWeight: 1,
                strokeColor: '#0091ea',
                fillColor: '#80d8ff',
                fillOpacity: 0.1,
                strokeStyle: 'dashed'
              }).setMap(this.map)
            })
            // 自适应地图视野
            this.map.setFitView()
          }
        })
      })
    },

    addLandmarks () {
      // 添加地标标记
      this.landmarks.forEach(landmark => {
        const marker = new AMap.Marker({
          position: landmark.position,
          title: landmark.name,
          icon: new AMap.Icon({
            size: new AMap.Size(32, 32),
            image: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_r.png',
            imageSize: new AMap.Size(32, 32)
          }),
          offset: new AMap.Pixel(-16, -32),
          animation: 'AMAP_ANIMATION_DROP',
          clickable: true
        })

        marker.on('click', () => {
          this.showInfoWindow(landmark)
        })

        marker.setMap(this.map)
      })
    },

    showInfoWindow (landmark) {
      this.currentMarker = landmark
      this.infoWindowVisible = true
    },

    toggle3D () {
      if (!this.map || this.viewChanging) return

      this.viewChanging = true

      // 切换视图前先保存当前中心点和缩放级别
      const currentCenter = this.map.getCenter()
      const currentZoom = this.map.getZoom()

      try {
        const targetMode = this.is3D ? '2D' : '3D'
        console.log(`尝试切换到${targetMode}模式...`)

        // 使用setStatus方法切换视图模式
        this.map.setStatus({
          viewMode: targetMode,
          jogEnable: targetMode === '3D',
          pitchEnable: targetMode === '3D',
          rotateEnable: targetMode === '3D',
          animateEnable: true
        })

        // 如果是3D模式，设置俯仰角，并添加控制条
        if (targetMode === '3D') {
          this.map.setPitch(45)
          this.addControlBar()
        } else {
          this.map.setPitch(0)
          this.removeControlBar()
        }

        // 保持相同的中心点和缩放级别
        this.map.setCenter(currentCenter)
        this.map.setZoom(currentZoom)

        // 切换成功
        this.is3D = !this.is3D
        console.log(`成功切换到${targetMode}模式`)
      } catch (error) {
        console.error('切换视图模式失败:', error)
        this.$message.error('切换视图模式失败，此浏览器可能不支持3D模式')
      } finally {
        this.viewChanging = false
      }
    },

    toggleTraffic () {
      this.showTraffic = !this.showTraffic
      this.trafficLayer.setMap(this.showTraffic ? this.map : null)
    },

    toggleBuildings () {
      this.showBuildings = !this.showBuildings
      this.buildingLayer.setMap(this.showBuildings ? this.map : null)
    },

    toggleMapStyle () {
      this.isDarkStyle = !this.isDarkStyle
      this.map.setMapStyle(this.isDarkStyle ? this.mapStyles.dark : this.mapStyles.light)

      // 安全地尝试设置天空颜色
      try {
        if (typeof this.map.setSkyCfg === 'function') {
          this.map.setSkyCfg({
            color: this.isDarkStyle ? '#1E1E1E' : '#C9E6FF'
          })
        }
      } catch (error) {
        console.warn('setSkyCfg 方法不可用:', error)
      }
    },

    resetView () {
      this.map.setStatus({
        zoom: 12,
        center: [106.504962, 29.533155],
        pitch: this.is3D ? 45 : 0,
        rotation: this.is3D ? -15 : 0
      }, {
        duration: 1000,
        easing: 'ease-in-out'
      })
    },

    initDroneMarkers () {
      this.drones.forEach(drone => {
        // 创建标记
        const marker = new AMap.Marker({
          position: drone.position,
          icon: new AMap.Icon({
            image: `${process.env.BASE_URL}drone-icon.png`,
            size: new AMap.Size(32, 32),
            imageSize: new AMap.Size(32, 32)
          }),
          offset: new AMap.Pixel(-16, -16),
          title: drone.id
        })

        // 添加标签
        const label = new AMap.Text({
          text: drone.id,
          anchor: 'center',
          offset: new AMap.Pixel(0, -40),
          style: {
            background: 'rgba(0,0,0,0.7)',
            color: '#fff',
            padding: '2px 6px',
            borderRadius: '10px',
            fontSize: '12px'
          }
        })

        // 添加点击事件
        marker.on('click', () => {
          this.selectedDrone = drone
        })

        // 添加信息窗体
        const info = new AMap.InfoWindow({
          content: `
            <div class="drone-info-window">
              <h4>无人机 ${drone.id}</h4>
              <p>高度: ${drone.altitude}米</p>
              <p>电量: ${drone.battery}%</p>
            </div>
          `,
          offset: new AMap.Pixel(0, -30)
        })

        // 鼠标悬停显示信息窗体
        marker.on('mouseover', () => {
          info.open(this.map, drone.position)
        })
        marker.on('mouseout', () => {
          info.close()
        })

        marker.setMap(this.map)
        label.setMap(this.map)
        this.markers[drone.id] = { marker, label }
      })
    },

    // 更新无人机位置时不再计算和设置角度
    updateDronePosition (drone, newPosition) {
      const markerObj = this.markers[drone.id]
      if (markerObj) {
        const { marker, label } = markerObj

        // 只更新位置，不更新角度
        marker.setPosition(newPosition)
        label.setPosition(newPosition)

        if (this.selectedDrone && this.selectedDrone.id === drone.id) {
          this.selectedDrone.position = newPosition
        }
      }
    },

    // 模拟无人机移动
    startDroneSimulation () {
      setInterval(() => {
        this.drones.forEach(drone => {
          // 模拟位置变化
          const newPosition = [
            drone.position[0] + (Math.random() - 0.5) * 0.001,
            drone.position[1] + (Math.random() - 0.5) * 0.001
          ]
          this.updateDronePosition(drone, newPosition)
          drone.position = newPosition
        })
      }, 2000) // 每2秒更新一次位置
    },

    toggleSatellite () {
      this.isSatellite = !this.isSatellite
      if (this.isSatellite) {
        this.map.setMapStyle('amap://styles/satellite')
      } else {
        this.map.setMapStyle('amap://styles/normal')
      }
    },

    // 添加3D控制条
    addControlBar () {
      if (!this.map || this.controlBar) return

      try {
        this.controlBar = new AMap.ControlBar({
          position: {
            top: '10px',
            right: '10px'
          }
        })
        this.map.addControl(this.controlBar)
      } catch (error) {
        console.error('添加3D控制条失败:', error)
      }
    },

    // 移除3D控制条
    removeControlBar () {
      if (!this.map || !this.controlBar) return

      try {
        this.map.removeControl(this.controlBar)
        this.controlBar = null
      } catch (error) {
        console.error('移除3D控制条失败:', error)
      }
    }
  },
  beforeDestroy () {
    if (this.map) {
      this.map.destroy()
    }
  }
}
</script>

<style lang="less" scoped>
.map-container {
  width: 100%;
  height: 600px;
  position: relative;

  .map {
    width: 100%;
    height: 100%;
  }

  .map-controls {
    position: absolute;
    top: 10px;
    left: 10px;
    z-index: 100;
    background: rgba(255, 255, 255, 0.9);
    padding: 10px;
    border-radius: 4px;
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
  }

  .info-window {
    position: absolute;
    bottom: 20px;
    left: 20px;
    z-index: 100;
    width: 250px;
  }

  .error-message {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 80%;
    z-index: 100;
  }

  .drone-info {
    position: absolute;
    top: 80px;
    right: 20px;
    width: 250px;
    z-index: 100;
    background: white;
    border-radius: 4px;
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);

    .ant-card-body {
      padding: 12px;
    }

    p {
      margin-bottom: 8px;
    }
  }

  :deep(.drone-info-window) {
    padding: 8px;

    h4 {
      margin: 0 0 8px 0;
      color: #1890ff;
    }

    p {
      margin: 4px 0;
      font-size: 12px;
    }
  }
}
</style>
